package com.itany.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itany.pojo.User;
import com.itany.user.service.IUserService;
import com.itany.vo.ActionResult;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by tyh on 2018/9/22.
 */
@Controller
@RequestMapping("/userserver")
public class UserController {

    @Reference
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/addUser")
    @ResponseBody
    public ActionResult addUser(User user){
        ActionResult ac= new ActionResult();
        userService.addUser(user);
        ac.setStatus(0);
        return ac;
    }

    @RequestMapping("/findUsers")
    public ModelAndView findUsers(@RequestParam(defaultValue = "1")Integer pageNo,
                                  @RequestParam(defaultValue = "10")Integer pageSize){
        PageInfo<User> pageInfo =  userService.findUsers(pageNo,pageSize);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("pageInfo",pageInfo);
        return new ModelAndView("userlist",map);
    }

    @RequestMapping("/login")
    public String login(User user, HttpServletResponse response){
        User u = userService.login(user);
        u.setPassword(null);
        // 生成token 将用户信息放入到redis
        String token = UUID.randomUUID().toString();
        //向redis里存入数据和设置缓存时间
        redisTemplate.opsForValue().set("USER_TOKEN::"+ token, JSON.toJSONString(u),1800, TimeUnit.SECONDS);
        // 将token放入到Cookie
        Cookie cookie = new Cookie("TT_TOKEN", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:http://localhost:9003/user/userserver/findUsers";
    }



    @RequestMapping("/casIndex")
    public String casIndex(HttpServletRequest request) {
        //获取cas给我们传递回来的对象，这个对象在Session中
        //session的 key是 CONST_CAS_ASSERTION
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal  = assertion.getPrincipal();
        String loginName =principal.getName();
        System.out.printf("登录用户名:",loginName);
        //获取自定义返回值的数据
        if (principal instanceof AttributePrincipal) {
            //cas传递过来的数据
            Map<String,Object> result =( (AttributePrincipal)principal).getAttributes();
            for(Map.Entry<String, Object> entry :result.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                System.out.printf(key+"-----------"+val);
            }
        }

        return "register";
    }

    @RequestMapping("/caslogout")
    public String caslogin(HttpSession session){
        session.invalidate();
        // 直接退出，走默认退出方式
        return "redirect:http://localhost:8443/cas/logout";
    }

}
